package com.aepryus.loom;

import java.util.*;
import javax.servlet.http.*;

public class Tracker {
	private List<HttpSession> sessions = Collections.synchronizedList(new Vector<HttpSession>());
	private Map<Thread,HttpSession> threadToSession = Collections.synchronizedMap(new HashMap<Thread,HttpSession>());

	public HttpSession getSession () {
		return threadToSession.get(Thread.currentThread());
	}
	public HttpSession[] getSessions () {
		pruneSessions();
		return sessions.toArray(new HttpSession[]{});
	}
	public void trackSession (HttpSession session) {
		if (!sessions.contains(session))
		    sessions.add(session);
		threadToSession.put(Thread.currentThread(),session);
	}
	public void expireSession (HttpSession session) {
		sessions.remove(session);
		List<Thread> removeList = new Vector<Thread>();
		for (Thread key : threadToSession.keySet()) {
			HttpSession test = threadToSession.get(key);
			if (session == test)
				removeList.add(key);
		}
		for (Thread thread : removeList)
			threadToSession.remove(thread);
	}
	private void pruneSessions () {
		List<HttpSession> removeSession = new Vector<HttpSession>();
		for (HttpSession session : sessions) {
			try {
				session.isNew();
			} catch (IllegalStateException e) {
				removeSession.add(session);
			}
		}
		for (HttpSession session : removeSession)
			sessions.remove(session);

		List<Thread> removeThread = new Vector<Thread>();
		for (Thread key : threadToSession.keySet()) {
			HttpSession session = threadToSession.get(key);
			try {
				session.isNew();
			} catch (IllegalStateException e) {
				removeThread.add(key);
			}
		}
		for (Thread thread : removeThread)
			threadToSession.remove(thread);
	}
}

